package org.victoria.common.security;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.victoria.common.utils.FrontUtils;
import org.victoria.common.utils.StringUtils;
import org.victoria.csms.domain.Privilege;
import org.victoria.csms.domain.Role;
import org.victoria.csms.domain.User;
import org.victoria.csms.service.UserService;

/**
 * Created by handoop on 2015/3/31.
 */
public class SimpleRealm extends AuthorizingRealm {

    private static final Logger logger = LoggerFactory.getLogger(SimpleRealm.class);

    @Autowired private UserService manager;
    /**
     * 授权
     * 权限验证
     * 为当前登录的Subject授予角色和权限
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.error("authorizating...");
        String username = (String) super.getAvailablePrincipal(principalCollection);
        User user = manager.getUserByAccount(username);
        if (user != null){
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            for (Role role : user.getRoles()){
                for (Privilege p : role.getPrivileges()){
                    info.addStringPermission(p.getName());
                }
            }
            return info;
        }
        return null;
    }

    /**
     * 登陆验证
     * 身份认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        logger.error("authenticating...");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String account = token.getUsername();
        if (!StringUtils.isEmpty(account)){
            User user = manager.getUserByAccount(account);
            if (user!=null){
                SecurityUtils.getSubject().getSession().setAttribute(FrontUtils.USER_KEY, user);
                return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
            }
        }
        return null;
    }
}
